package gewu.suleju.controller;

import gewu.suleju.anno.FormToken;
import gewu.suleju.consts.RedisConst;
import gewu.suleju.model.pojo.RenterReservation;
import gewu.suleju.model.vo.Result;
import gewu.suleju.sevice.imp.RenterReservationServiceImp;
import gewu.suleju.util.JWTUtil;
import gewu.suleju.util.WebSocketProcess;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static jdk.nashorn.internal.runtime.GlobalFunctions.decodeURIComponent;

@RestController
@RequestMapping("orderhouse")
public class OrderSeeHouse {
    //几秒钟内不可重复提交aop+全局异常处理，redis
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RenterReservationServiceImp renterReservationServiceImp;
    @FormToken(repeat = true)
    @RequestMapping("submit")
    public Result repeatsubmit(String formToken, String houseId,String orderDate, HttpServletRequest request){
        //保存到数据库
        //拿到token里的用户id
        String userToken = request.getHeader("userToken");
        Claims claims = JWTUtil.checkJWT(userToken);
        String userId = String.valueOf(claims.get("id"));
        //获取表单的值
        String[] data = orderDate.split("&");
       // String name = (String) decodeURIComponent(data[0].split("=")[1],true);
        String name = data[0].split("=")[1];
        String phone = data[1].split("=")[1];
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date newTime = null;
        try {
            newTime = format.parse(data[2].split("=")[1]);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        RenterReservation renterReservation = new RenterReservation(name,phone,newTime,Integer.parseInt(userId),Integer.parseInt(houseId),1);
        renterReservationServiceImp.save(renterReservation);
        //实现经纪人消息推送

        return  new Result("200","提交成功");
    }
    @RequestMapping("sendBroker")
    public Result sendBroker(String brokerId ,String userId,String houseId){
        redisTemplate.opsForValue().set(brokerId,userId+"!"+houseId);
        redisTemplate.convertAndSend(RedisConst.ORDERCHANNEL,brokerId);
        return new Result();
    }
}
